package com.xwrite.toolkit;

import com.intellij.openapi.options.Configurable;
import com.intellij.openapi.project.Project;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;

/**
 * Provides controller functionality for application settings.
 */
final class AppSettingsConfigurable implements Configurable {

    private final AppSettingsStorage settingsStorage;

    private AppSettingsComponent settingsComponent;

    public AppSettingsConfigurable(@NotNull Project project) {
        this.settingsStorage = new AppSettingsStorage(project);

    }

    @Nls(capitalization = Nls.Capitalization.Title)
    @Override
    public String getDisplayName() {
        return "Flutter Build Runner";
    }

    @Override
    public JComponent getPreferredFocusedComponent() {
        return settingsComponent.getPreferredFocusedComponent();
    }

    @Nullable
    @Override
    public JComponent createComponent() {
        settingsComponent = new AppSettingsComponent();
        return settingsComponent.getPanel();
    }

    @Override
    public boolean isModified() {
        AppSettingsState settings = settingsStorage.get();
        boolean modified = !settingsComponent.getSdkPathText().equals(settings.flutterSdkPath);
        modified |= settingsComponent.getDeleteConflictingOutputs() != settings.isDeleteConflictingOutputs;
        return modified;
    }

    @Override
    public void apply() {
        AppSettingsState settings = settingsStorage.get();
        settings.flutterSdkPath = settingsComponent.getSdkPathText();
        settings.isDeleteConflictingOutputs = settingsComponent.getDeleteConflictingOutputs();
        settingsStorage.set(settings);
    }

    @Override
    public void reset() {
        AppSettingsState settings = settingsStorage.get();
        settingsComponent.setSdkPathText(settings.flutterSdkPath);
        settingsComponent.setDeleteConflictingOutputs(settings.isDeleteConflictingOutputs);
    }

    @Override
    public void disposeUIResources() {
        settingsComponent = null;
    }

}